package com.sportizz.sport.row;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.Instances;
import android.provider.CalendarContract.Reminders;
import android.text.InputType;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;

import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.UiLifecycleHelper;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.FbDialog;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.widget.FacebookDialog;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;
import com.sportizz.model.ImageLoader;
import com.sportizz.model.Player;
import com.sportizz.sport.AlertDialogManager;
import com.sportizz.sport.DatabaseAdapter;
import com.sportizz.sport.Fb_dialog_box;
import com.sportizz.sport.MainActivity;
import com.sportizz.sport.R;
import com.sportizz.sport.Setting_Act;
import com.sportizz.sport.StartActivity;
import com.sportizz.sport.Utils;

public class TeamRow implements Row {

	private final Player player;
	private final LayoutInflater inflater;
	private final Activity act_context;
	private DatabaseAdapter mDbHelper;

	private boolean tpress1 = false;
	private boolean tpress2 = false;
	private String country_code;
	StartActivity sa = new StartActivity();
	String t_channel1;
	String t_channel2;
	String t_channel3;
	
	Context con;
	ImageLoader imgLoader;
	
	AlertDialog.Builder alertDialog = null;
	Typeface font_team;
	AlertDialogManager alert = new AlertDialogManager();

	private AsyncFacebookRunner mAsyncRunner;
	
	private static String APP_ID = "587247084685835"; // Replace with your App ID
	 
	 private Facebook facebook = new Facebook(APP_ID);
	 
	public ProgressDialog pd;
	
	public static final int REQUEST_PASSPORT_PURCHASE = 2012;

	public TeamRow(LayoutInflater inflater, Player player, Context _context) {
		this.inflater = inflater;
		this.player = player;
		this.act_context = (Activity) _context;
		this.con=_context;
		
		imgLoader = new ImageLoader(con.getApplicationContext());
		
	}

	@SuppressLint({ "NewApi", "SimpleDateFormat" })
	@Override
	public View getView(View convertView) {

		mAsyncRunner = new AsyncFacebookRunner(StartActivity.facebook);
		
		country_code = StartActivity.GetCountryCode(act_context);

		final ViewHolder holder;
		View view;

		if (convertView == null) {
			ViewGroup viewGroup = (ViewGroup) inflater.inflate(
					R.layout.new_custom_row_team, null);

			holder = new ViewHolder(
					 
					(LinearLayout) viewGroup.findViewById(R.id.head_rel_team),
					(ImageView) viewGroup.findViewById(R.id.new_image_t1),
					(ImageView) viewGroup.findViewById(R.id.new_image_t2),
					(TextView) viewGroup.findViewById(R.id.txt_tgame),
					(TextView) viewGroup.findViewById(R.id.txt_tmatch),
					(TextView) viewGroup.findViewById(R.id.new_champ_txt_team),
					(TextView) viewGroup.findViewById(R.id.new_txt_team1),
					(TextView) viewGroup.findViewById(R.id.new_txt_team2),
					(TextView) viewGroup.findViewById(R.id.new_txt_tday),
					(TextView) viewGroup.findViewById(R.id.new_txt_tdate),
					(TextView) viewGroup.findViewById(R.id.new_sport_t_name),
					(TextView) viewGroup.findViewById(R.id.new_img_t_channel2),
					(TextView) viewGroup.findViewById(R.id.new_img_t_channel1),
					(TextView) viewGroup.findViewById(R.id.new_img_t_channel3),
					(Button) viewGroup.findViewById(R.id.new_btn_t_follow1),
					(Button) viewGroup.findViewById(R.id.new_btn_t_follow2),
					(Button) viewGroup.findViewById(R.id.new_btn_team_addcal),
					(Button) viewGroup.findViewById(R.id.ticket_team));

			viewGroup.setTag(holder);

			view = viewGroup;
		} else {
			holder = (ViewHolder) convertView.getTag();

			view = convertView;
		}

		
		Typeface sport_font = Typeface.createFromAsset(act_context.getAssets(),
				"hel57.ttf");
		
		
		holder.t_follow1.setTypeface(sport_font);
		holder.t_follow2.setTypeface(sport_font);

		holder.teamname1.setTypeface(sport_font);
		holder.teamname1.setSelected(true);
		holder.teamname2.setTypeface(sport_font);
		holder.teamname2.setSelected(true);

		holder.t_follow1.setTag(player.getplayer_code1().toString());
		holder.t_follow2.setTag(player.getplayer_code2().toString());

		if (player.geti_foll() == true) {
			holder.t_follow1.setVisibility(View.GONE);
			holder.t_follow2.setVisibility(View.GONE);

		}
		

		holder.t_follow1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				mDbHelper = new DatabaseAdapter(act_context);
				mDbHelper.open();

				StartActivity.foll_count = StartActivity.follow_count.getInt(
						"follow_count", 0);

				Log.e("suraj", "StartActivity.foll_count = "
						+ StartActivity.foll_count);

				String emailString = com.sportizz.model.UserEmailFetcher
						.getEmail(act_context);

				String purchase_json = Utils.readJsonFeed(
						"http://sportizza.com/interface/check_android_purchase.php?email="
								+ emailString + "", act_context);

				Log.d("suraj", "purchase_json for " + emailString + " = "
						+ purchase_json);

//				if (StartActivity.foll_count < StartActivity.limited_follow
//						.getInt("max_follow", 3)
//						&& StartActivity.foll_count >= 0) {

					if (holder.t_follow1.getText().toString()
									.equals("FOLLOW")) {

						AsyncTask<Void, Void, Void> wait = new AsyncTask<Void, Void, Void>() {

							@Override
							protected void onPostExecute(
									Void result) {
								super.onPostExecute(result);
								pd.dismiss();
								mDbHelper.close();
							}

							@Override
							protected void onPreExecute() {
								
								pd = ProgressDialog.show(
										act_context, "",
										"Following...", true);
								super.onPreExecute();
							}

							@Override
							protected Void doInBackground(
									Void... params) {

						try {
							String device_id = sa.GetDeviceID(act_context);

							Log.d("suraj",
									"Team_id =" + player.getplayer_code1());
							Log.d("suraj", "Team_id =" + player.getplayer1());

							String national = null;

							if (player.getplayer1_country().equals(
									player.getplayer1_club5())) {
								national = player.getplayer1_country();
							} else {
								national = player.getplayer_code1();
							}

							Log.v("suraj", "NATIONAL = " + national);
							
							Long ins1_c = mDbHelper.insert_follow_info(player.getplayer_code1(),player.getplayer1(),
									player.getsport_code(), player.getsport(),
									national, player.getteam(),"P");

							String response = Utils
									.getJSONString("http://sportizza.com/interface/ios_follow.php?dev_id="
											+ device_id
											+ "&iso_cd="
											+ country_code
											+ "&follow="
											+ player.getplayer_code1()
											+ "&follow_cs=-1");

							if (ins1_c != 0) {

								Thread t = new Thread(
										new Runnable() {
											public void run() {

												act_context.runOnUiThread(new Runnable() {
													public void run() {
								Toast.makeText(
										act_context.getApplicationContext(),
										"Added to I follow", Toast.LENGTH_SHORT)
										.show();
								Log.d("suraj", "follow success..");

								holder.t_follow1.setText("UNFOLLOW");

								MainActivity.playerAll.add(player
										.getplayer_code1());

								Log.d("suraj", "PLAYER = "
										+ MainActivity.playerAll);

								StartActivity.foll_count++;

								SharedPreferences.Editor editor = StartActivity.follow_count
										.edit();
								editor.putInt("follow_count",
										StartActivity.foll_count);
								editor.commit();
													}
												});
											}
										});
								t.start();
							} else {
								Toast.makeText(
										act_context.getApplicationContext(),
										"Error during follow",
										Toast.LENGTH_SHORT).show();
							}

							tpress1 = true;
//							mDbHelper.close();
						} catch (Exception e) {
 
						}
						return null;
							}
						};
						wait.execute();
					} 
//					else if (tpress1 == true) {
//						Log.d("suraj", "Already follow");
//					}

//				} else {
//
//					Toast.makeText(act_context.getApplicationContext(),
//							"Reach to Maximum Follow count....",
//							Toast.LENGTH_LONG).show();
//
//					Pay_dialog_box pdb = new Pay_dialog_box(act_context);
//					pdb.show();
//
//				}
			}
		});

		holder.t_follow2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mDbHelper = new DatabaseAdapter(act_context);
				mDbHelper.open();

				StartActivity.foll_count = StartActivity.follow_count.getInt(
						"follow_count", 0);

				Log.e("suraj", "StartActivity.foll_count = "
						+ StartActivity.foll_count);

//				if (StartActivity.foll_count < StartActivity.limited_follow
//						.getInt("max_follow", 3)
//						&& StartActivity.foll_count >= 0) {

					if (holder.t_follow2.getText().toString()
									.equals("FOLLOW")) {

						AsyncTask<Void, Void, Void> wait = new AsyncTask<Void, Void, Void>() {

							@Override
							protected void onPostExecute(
									Void result) {
								super.onPostExecute(result);
								pd.dismiss();
								mDbHelper.close();
							}

							@Override
							protected void onPreExecute() {
								
								pd = ProgressDialog.show(
										act_context, "",
										"Following...", true);
								super.onPreExecute();
							}

							@Override
							protected Void doInBackground(
									Void... params) {
						try {

							String device_id = sa.GetDeviceID(act_context);

							Log.d("suraj",
									"Team_id =" + player.getplayer_code2());

							Log.d("suraj", "Team_id =" + player.getplayer2());

							String national = null;

							if (player.getplayer2_country().equals(
									player.getplayer2_club5())) {
								national = player.getplayer2_country();
							} else {
								national = player.getplayer_code2();
							}

							
							Long in_c = mDbHelper.insert_follow_info(player.getplayer_code2(),player.getplayer2(),
									player.getsport_code(), player.getsport(),
									national, player.getteam(),"P");

							String response1 = Utils
									.getJSONString("http://sportizza.com/interface/ios_follow.php?dev_id="
											+ device_id
											+ "&iso_cd="
											+ country_code
											+ "&follow="
											+ player.getplayer_code2()
											+ "&follow_cs=-1");

							if (in_c != 0) {

								Thread t = new Thread(
										new Runnable() {
											public void run() {

												act_context.runOnUiThread(new Runnable() {
													public void run() {
								Toast.makeText(
										act_context.getApplicationContext(),
										"Added to I follow", Toast.LENGTH_SHORT)
										.show();
								Log.d("suraj", "follow success..");

								holder.t_follow2.setText("UNFOLLOW");

								MainActivity.playerAll.add(player
										.getplayer_code2());

								StartActivity.foll_count++;

								SharedPreferences.Editor editor = StartActivity.follow_count
										.edit();
								editor.putInt("follow_count",
										StartActivity.foll_count);
								editor.commit();

													}
												});
											}
											});
								t.start();
								
							} else {
								Toast.makeText(
										act_context.getApplicationContext(),
										"Error during follow",
										Toast.LENGTH_SHORT).show();
							}

							tpress2 = true;
//							mDbHelper.close();

						} catch (Exception e) {
						}
						return null;
							}
						};
						wait.execute();
						
					} 
//					else if (tpress2 == true) {
//						Log.d("suraj", "Already follow");
//					}
//				}
//			   else {
//
//					Toast.makeText(act_context.getApplicationContext(),
//							"Reach to Maximum Follow count....",
//							Toast.LENGTH_LONG).show();
//
//					Pay_dialog_box pdb = new Pay_dialog_box(act_context);
//					pdb.show();
//
//				}

			}

		});

		holder.btn_team_cal.setTag(player.getDate1().toString());

		holder.btn_team_cal.setTypeface(sport_font);
		
		holder.btn_team_cal.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
//				if (MainActivity.check_cal.isChecked() == true) {
					String date_str = (String) holder.btn_team_cal.getTag();

					Log.v("suraj", "DAte = " + date_str);

					Long start_date_mili = null;

					String title = player.getplayer1() + " Vs "
							+ player.getplayer2() + " - "
							+ player.getChamp_name();

					SimpleDateFormat dateFormat11 = new SimpleDateFormat(
							"dd-MM-yyyy hh:mm a");

					Date date11 = null;

					try {
						date11 = dateFormat11.parse(date_str);
					} catch (ParseException e) {
						e.printStackTrace();
					}

					start_date_mili = date11.getTime();

					long begin = start_date_mili;
					long end = start_date_mili + 30 * 60 * 1000;// ending time
																// in
																// milliseconds
					String[] proj = new String[] { Instances._ID,
							Instances.TITLE, Instances.BEGIN, Instances.END,
							Instances.EVENT_ID };

					Cursor cursor = Instances.query(
							act_context.getContentResolver(), proj, begin, end);

					cursor.moveToFirst();

					Log.v("suraj", "Cursor = " + cursor);

					Log.v("suraj", "Cursor COUNT = " + cursor.getCount());

					if (cursor.getCount() > 0) {

						String title_cal = cursor.getString(cursor
								.getColumnIndex("title"));

						if (title_cal.equals(title)) {
							Log.i("suraj",
									"Cursor = "
											+ cursor.getString(cursor
													.getColumnIndex("title")));

							Toast.makeText(act_context,
									"Already Added to Calendar..",
									Toast.LENGTH_SHORT).show();
						} else {
							Log.i("suraj",
									"Setting_Act.check_cal.isChecked() = "
											+Setting_Act.check_cal.isChecked());

							Log.i("suraj", "Add to calendar = " + title);

							addToCalendar(act_context, player.getChamp_name(),
									player.getgametext(), title,
									start_date_mili,
									start_date_mili + 30 * 60 * 1000);
							Toast.makeText(act_context, "Added to Calendar..",
									Toast.LENGTH_SHORT).show();

						}
					} else {
						Log.i("suraj", "Setting_Act.check_cal.isChecked() = "
								+ Setting_Act.check_cal.isChecked());

						Log.i("suraj", "Add to calendar = " + title);

						addToCalendar(act_context, player.getChamp_name(),
								player.getgametext(), title, start_date_mili,
								start_date_mili + 30 * 60 * 1000);
						Toast.makeText(act_context, "Added to Calendar..",
								Toast.LENGTH_SHORT).show();
					}
//				} else {
//					Toast.makeText(act_context,
//							"Access Calendar is off in setting",
//							Toast.LENGTH_SHORT).show();
//				}
			}

		});
/*
		holder.btn_fbshare.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			
				Log.e("suraj","Session =="+ Session.getActiveSession().isOpened());
				
				if(Session.getActiveSession().isOpened())
				{
					postToWall(player.getplayer1(),player.getplayer2(),player.getChamp_name(),player.getDate());
				}
				else
				{
					
//					Fb_dialog_box pdb = new Fb_dialog_box(act_context);
//					pdb.show();
					
//					Intent intent_row=new Intent(act_context,Sample_Act_FB.class);
//					act_context.startActivity(intent_row);
					
//					Intent data=new Intent();
//					data.putExtra("key", "main");
//					setResult(300, data);
//					Log.e("suraj","Login Completed...");
//					try {
//						Thread.sleep(1500);
//					} catch (InterruptedException e) {
//						e.printStackTrace();
//					}
//					if(Session.getActiveSession().isOpened())
//					{
//						postToWall(player.getplayer1(),player.getplayer2(),player.getChamp_name(),player.getDate());
//					}
//					else
//					{
//						return;
//					}
					
				}
				
				
//				String access_token1 = StartActivity.mPrefs.getString("access_token", null);
//				if (access_token1 != null) {
//					facebook.setAccessToken(access_token1);
//					postToWall(player.getplayer1(),player.getplayer2(),player.getChamp_name(),player.getDate());
//					Log.d("FB Sessions", "" + StartActivity.facebook.isSessionValid());
//				} else 
//				{
////					loginToFacebook();
//					postToWall(player.getplayer1(),player.getplayer2(),player.getChamp_name(),player.getDate());
//				}
			}
		});
		*/
		String player_code1 = null;

		if (player.gettablet() == false) {
			if (player.getplayer1_club5().equalsIgnoreCase(
					player.getplayer1_country())) {

				player_code1 = "" + StartActivity.get_img_location
						+ "phone/country/"
						+ player.getplayer1_country() + ".png";
				
//				new imageTask(holder.team_image1).execute(player_code1);
				
				int loader = getImgLoader(player.getsport_code());
				
				imgLoader.DisplayImage(player_code1,loader,holder.team_image1);
				
				
			} else {
				player_code1 = "" + StartActivity.get_img_location
						+ "phone/" + player.getsport_code() + "/"
						+ player.getplayer_code1() + ".png";
				
//				new imageTask(holder.team_image1).execute(player_code1);
				
				int loader = getImgLoader(player.getsport_code());
				
				imgLoader.DisplayImage(player_code1,loader,holder.team_image1);
			}

			if (player.getplayer2_club5().equalsIgnoreCase(
					player.getplayer2_country())) {
				String player_code2 = "" + StartActivity.get_img_location
						+ "phone/country/"
						+ player.getplayer2_country() + ".png";
				
//				new imageTask(holder.team_image2).execute(player_code2);
				int loader = getImgLoader(player.getsport_code());
				
				imgLoader.DisplayImage(player_code2,loader,holder.team_image2);
			}

			else {
				String player_code2 = "" + StartActivity.get_img_location
						+ "phone/" + player.getsport_code() + "/"
						+ player.getplayer_code2() + ".png";
				
//				new imageTask(holder.team_image2).execute(player_code2);
				int loader = getImgLoader(player.getsport_code());
				
				imgLoader.DisplayImage(player_code2,loader,holder.team_image2);
				
			}
		} else {

			if (player.getplayer1_club5().equalsIgnoreCase(
					player.getplayer1_country())) {

				player_code1 = "" + StartActivity.get_img_location
						+ "pad/country/"
						+ player.getplayer1_country() + "@2x.png";
				
//				new imageTask(holder.team_image1).execute(player_code1);
				
				int loader = getImgLoader(player.getsport_code());
				
				imgLoader.DisplayImage(player_code1,loader,holder.team_image1);
				
			} else {
				player_code1 = "" + StartActivity.get_img_location
						+ "pad/" + player.getsport_code() + "/"
						+ player.getplayer_code1() + "@2x.png";
				
//				new imageTask(holder.team_image1).execute(player_code1);
				int loader = getImgLoader(player.getsport_code());
				
				imgLoader.DisplayImage(player_code1,loader,holder.team_image1);
				
			}

			if (player.getplayer2_club5().equalsIgnoreCase(
					player.getplayer2_country())) {

				String player_code2 = "" + StartActivity.get_img_location
						+ "pad/country/"
						+ player.getplayer2_country() + "@2x.png";
				
//				new imageTask(holder.team_image2).execute(player_code2);
				int loader = getImgLoader(player.getsport_code());
				
				imgLoader.DisplayImage(player_code2,loader,holder.team_image2);
				

			} else {
				String player_code2 = "" + StartActivity.get_img_location
						+ "pad/" + player.getsport_code() + "/"
						+ player.getplayer_code2() + "@2x.png";
				
//				new imageTask(holder.team_image2).execute(player_code2);
				int loader = getImgLoader(player.getsport_code());
				
				imgLoader.DisplayImage(player_code2,loader,holder.team_image2);
				
			}
		}

		if (player.getplayer1() == null
				|| player.getplayer1().equalsIgnoreCase("null")) {

		} else {
			holder.teamname1.setText(player.getplayer1());
			holder.teamname1
					.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
			holder.teamname1.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
		}

		if (player.getplayer2() == null
				|| player.getplayer2().equalsIgnoreCase("null")) {

		} else {
			holder.teamname2.setText(player.getplayer2());
			holder.teamname2
					.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
			holder.teamname2.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
		}


		String[] team_date = player.getDate().split(" ");
		
		holder.teamdate.setText(team_date[0]+"\n"+team_date[1]+" "+team_date[2]);
		holder.teamdate.setTypeface(sport_font);

		holder.teamday.setText(" "+player.getDay());
		holder.teamday.setTypeface(sport_font);

		holder.sport_name.setText(player.getsport());
		holder.sport_name.setTypeface(sport_font);
//		holder.sport_name.setTextSize(10);
		holder.sport_name.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
		holder.sport_name.setGravity(Gravity.LEFT);

		holder.teamchamp.setText(" "+player.getChamp_name());

		if(player.getgametext()==null || player.getgametext().equals("")||player.getgametext().contains("null"))
		{
			holder.game_txt.setText("");
		}else
		{
			holder.game_txt.setText(player.getgametext());
			holder.game_txt.setTypeface(sport_font);
		}
		
		if(player.getmatchtext()==null || player.getmatchtext().equals("")||player.getmatchtext().contains("null"))
		{
			holder.match_txt.setText("");
		}else
		{
			holder.match_txt.setText(player.getmatchtext());
			holder.match_txt.setTypeface(sport_font);
		}
		
		if(player.getticket().equals("hide"))
		{
			 holder.ticket.setVisibility(View.INVISIBLE);
		}
		
		holder.ticket.setTypeface(sport_font);
		
		holder.ticket.setOnClickListener(new OnClickListener() {
	
			@Override
			public void onClick(View arg0) {
		
				if(player.getticket().equals("") || player.getticket()==null)
				{
					Toast.makeText(act_context, "Check back later..", Toast.LENGTH_SHORT).show();
				}
				else
				{
					Fb_dialog_box pdb = new Fb_dialog_box(act_context,player.getticket());
					pdb.show();
				}
				
			}
		});

			
		
		if(player.getup_y_team()==true)
		{
			holder.linearLayout.setVisibility(View.GONE);
		}
		

		Bitmap bi_result = null ;
		
		try {
			 bi_result = BitmapFactory.decodeStream(act_context
					.getResources()
					.getAssets()
					.open("sport_small/"+ player.getsport_code() + "_S.png"));
		} catch (IOException e1) {
			e1.printStackTrace();
			try {
				 bi_result = BitmapFactory.decodeStream(act_context
						.getResources()
						.getAssets()
						.open("sport_small/GAM_S.png"));
			} catch (IOException e2) {
			}
		}
		
		if(bi_result==null)
		{
			holder.teamchamp.setCompoundDrawablesWithIntrinsicBounds( R.drawable.team_selected, 0, 0, 0);
			
			holder.teamchamp.setTypeface(sport_font);
			holder.teamchamp.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
		}
		else
		{
		Bitmap	bitmap = Bitmap.createScaledBitmap(bi_result,20, 20, true);
		
		Drawable tmpDraw = (Drawable) new BitmapDrawable(act_context.getResources(),bitmap);
		
		holder.teamchamp.setCompoundDrawablesWithIntrinsicBounds( tmpDraw, null, null, null);
		
		
		holder.teamchamp.setTypeface(sport_font);
		holder.teamchamp.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
		}
		
		
		Log.d("suraj", "playerAll = " + MainActivity.playerAll);

		Log.d("suraj",
				"follow_btn1.getTag() = "
						+ MainActivity.playerAll.contains(holder.t_follow1
								.getTag().toString()) + "=="
						+ holder.t_follow1.getTag().toString());
		Log.d("suraj",
				"follow_btn2.getTag() = "
						+ MainActivity.playerAll.contains(holder.t_follow2
								.getTag().toString()) + "=="
						+ holder.t_follow2.getTag().toString());

		if (MainActivity.playerAll != null) {
			if (MainActivity.playerAll.contains(holder.t_follow1.getTag()
					.toString()) == true) {
				holder.t_follow1.setText("UNFOLLOW");
			} else {
				holder.t_follow1.setText("FOLLOW");
			}

			if (MainActivity.playerAll.contains(holder.t_follow2.getTag()
					.toString()) == true) {
				holder.t_follow2.setText("UNFOLLOW");
			} else {
				holder.t_follow2.setText("FOLLOW");
			}
		}

//		InputStream is1 = null;
//		try {
//			if (player.gettablet() == false) {
//				is1 = act_context
//						.getResources()
//						.getAssets()
//						.open("new_sports/" + player.getsport_code()
//								+ ".png");
//				Bitmap res1 = BitmapFactory.decodeStream(is1);
//
//				Log.i("suraj", "" + res1);
//
//				Bitmap output1 = Bitmap.createBitmap(res1.getWidth(),
//						res1.getHeight(), Bitmap.Config.ARGB_8888);
//				Canvas canvas1 = new Canvas(output1);
//
//				Paint paint = new Paint();
//				Rect rect = new Rect(0, 0, res1.getWidth(), res1.getHeight());
//				RectF rectF = new RectF(rect);
//				float roundPx1 = 8f;
//
//				paint.setAntiAlias(true);
//				canvas1.drawARGB(0, 0, 0, 0);
//				paint.setColor(0xff424242);
//				canvas1.drawRoundRect(rectF, roundPx1, roundPx1, paint);
//				paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
//				canvas1.drawBitmap(res1, rect, rect, paint);
//
//				holder.team_image1.setImageBitmap(output1);
//				holder.team_image1.setScaleType(ScaleType.FIT_CENTER);
//
//				holder.team_image2.setImageBitmap(output1);
//				holder.team_image2.setScaleType(ScaleType.FIT_CENTER);
//			} else if (player.gettablet() == true) {
//				is1 = act_context
//						.getResources()
//						.getAssets()
//						.open("new_sports/" + player.getsport_code()
//								+ ".png");
//
//				Bitmap res2 = BitmapFactory.decodeStream(is1);
//
//				Log.i("suraj", "" + res2);
//
//				Bitmap output1 = Bitmap.createBitmap(res2.getWidth(),
//						res2.getHeight(), Bitmap.Config.ARGB_8888);
//				Canvas canvas1 = new Canvas(output1);
//
//				Paint paint = new Paint();
//				Rect rect = new Rect(0, 0, res2.getWidth(), res2.getHeight());
//				RectF rectF = new RectF(rect);
//				float roundPx1 = 8f;
//
//				paint.setAntiAlias(true);
//				canvas1.drawARGB(0, 0, 0, 0);
//				paint.setColor(0xff424242);
//				canvas1.drawRoundRect(rectF, roundPx1, roundPx1, paint);
//				paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
//				canvas1.drawBitmap(res2, rect, rect, paint);
//
//				holder.team_image1.setImageBitmap(output1);
//				holder.team_image1.setScaleType(ScaleType.FIT_CENTER);
//
//				holder.team_image2.setImageBitmap(output1);
//				holder.team_image2.setScaleType(ScaleType.FIT_CENTER);
//			}
//		} catch (Exception e) {
//		}

		Log.d("suraj",
				"player.getchannel_code1() = " + player.getchannel_code1());
		Log.d("suraj",
				"player.getchannel_code2() = " + player.getchannel_code2());
		Log.d("suraj",
				"player.getchannel_code3() = " + player.getchannel_code3());

		if (player.getchannel_code1().equals("null")
				|| player.getchannel_code1().equals("NONE")
				|| player.getchannel_code1() == null) {
			holder.channel1.setVisibility(View.INVISIBLE);
		} else {
			holder.channel1.setVisibility(View.VISIBLE);
		}
		//
		if (player.getchannel_code2().equals("null")
				|| player.getchannel_code2().equals("NONE")
				|| player.getchannel_code2() == null) {
			holder.channel2.setVisibility(View.INVISIBLE);
		} else {
			holder.channel2.setVisibility(View.VISIBLE);
		}
		//
		if (player.getchannel_code3().equals("null")
				|| player.getchannel_code3().equals("NONE")
				|| player.getchannel_code3() == null) {
			holder.channel3.setVisibility(View.INVISIBLE);
		} else {
			holder.channel3.setVisibility(View.VISIBLE);
		}

		holder.channel1.setTypeface(sport_font);
		holder.channel2.setTypeface(sport_font);
		holder.channel3.setTypeface(sport_font);
		
		holder.channel1.setText(player.getchannel_code1());
		holder.channel2.setText(player.getchannel_code2());
		holder.channel3.setText(player.getchannel_code3());

		// else
		// {
		// holder.channel3.setText(player.getchannel_code3());
		// }

		// if (player.gettablet() == false) {
		// t_channel1 = "" + StartActivity.get_img_location
		// + "/ss/images/phone/TV/" + player.getchannel_code1()
		// + ".png";
		// t_channel2 = "" + StartActivity.get_img_location
		// + "/ss/images/phone/TV/" + player.getchannel_code2()
		// + ".png";
		// t_channel3 = "" + StartActivity.get_img_location
		// + "/ss/images/phone/TV/" + player.getchannel_code3()
		// + ".png";
		//
		// new imageTask_channel().execute(holder.channel2, holder.channel1,
		// holder.channel3);
		// } else {
		// t_channel1 = "" + StartActivity.get_img_location
		// + "/ss/images/phone/TV/" + player.getchannel_code1()
		// + "@2x.png";
		// t_channel2 = "" + StartActivity.get_img_location
		// + "/ss/images/phone/TV/" + player.getchannel_code2()
		// + "@2x.png";
		// t_channel3 = "" + StartActivity.get_img_location
		// + "/ss/images/phone/TV/" + player.getchannel_code3()
		// + "@2x.png";
		//
		// new imageTask_channel().execute(holder.channel2, holder.channel1,
		// holder.channel3);
		// }

		return view;

	}

	@SuppressWarnings("deprecation")
	protected void loginToFacebook() {

		  String access_token = StartActivity.mPrefs.getString("access_token", null);
		  long expires = StartActivity.mPrefs.getLong("access_expires", 0);
		 
		  if (access_token != null) {
		   facebook.setAccessToken(access_token);
		   SharedPreferences.Editor editor = StartActivity.mPrefs.edit();
	       editor.putString("access_token",
	         facebook.getAccessToken());
	       editor.putLong("access_expires",
	         facebook.getAccessExpires());
	       editor.commit();
		   Log.d("FB Sessions", "" + facebook.isSessionValid());
		  }
		 
		  if (expires != 0) {
		   facebook.setAccessExpires(expires);
		  }
		 
		  if (!facebook.isSessionValid()) {
		   facebook.authorize(act_context,
		     new String[] { "email", "publish_stream" },
		     new DialogListener() {
		 
		      @Override
		      public void onCancel() {
		      }
		 
		      @Override
		      public void onComplete(Bundle values) {
		       SharedPreferences.Editor editor = StartActivity.mPrefs.edit();
		       editor.putString("access_token",
		         facebook.getAccessToken());
		       editor.putLong("access_expires",
		         facebook.getAccessExpires());
		       editor.commit();
		      }
		 
		      @Override
		      public void onError(DialogError error) {
		 
		      }
		 
		      @Override
		      public void onFacebookError(FacebookError fberror) {
		 
		      }
		 
		     });
		  }
	}

	@SuppressWarnings("deprecation")
	protected void postToWall(String player1,String player2,String champ_name,String date) {
		
		String[] date_only=date.split(" ");
		
		Log.w("suraj","TEAM ROW ==="+Session.getActiveSession());
			
		final Bundle postParams = new Bundle();
	     postParams.putString("name", player1 +" Vs " +player2);
	     postParams.putString("caption", champ_name);
	     postParams.putString("description", date_only[0]);
	     postParams.putString("link", "https://play.google.com/store/apps/details?id=com.sportizz.sport&hl=en");
	     postParams.putString("picture", "http://sportizza.com/img/phones.png");
		
		act_context.runOnUiThread(new Runnable()
	    {
	        @Override
	        public void run() 
	        {
	            WebDialog feedDialog = new WebDialog.FeedDialogBuilder(act_context, Session.getActiveSession(), postParams).build();
	            feedDialog.show();
	        }
	    });
//		
//		 Bundle postParams = new Bundle();
//	     postParams.putString("name", player1 +" Vs " +player2);
//	     postParams.putString("caption", champ_name);
//	     postParams.putString("description", date_only[0]);
//	     postParams.putString("link", "https://play.google.com/store/apps/details?id=com.sportizz.sport&hl=en");
//	     postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
//
//	     Log.d("suraj","SESSION =="+Session.getActiveSession());
//
//	     WebDialog feedDialog = (
//	         new WebDialog.FeedDialogBuilder(act_context,
//	             Session.getActiveSession(),
//	             postParams))
//	         .setOnCompleteListener(new OnCompleteListener() {
//
//				@Override
//				public void onComplete(Bundle values, FacebookException error) {
//
//					if (error == null) {
//	                     // When the story is posted, echo the success
//	                     // and the post Id.
//	                     final String postId = values.getString("post_id");
//	                     if (postId != null) {
//	                         Toast.makeText(act_context,
//	                             "Posted story, id: "+postId,
//	                             Toast.LENGTH_SHORT).show();
//	                     } else {
//	                         Toast.makeText(act_context, 
//	                             "Publish cancelled", 
//	                             Toast.LENGTH_SHORT).show();
//	                     }
//	                 } else if (error instanceof FacebookOperationCanceledException) {
//	                     Toast.makeText(act_context, 
//	                         "Publish cancelled", 
//	                         Toast.LENGTH_SHORT).show();
//	                 } else {
//	                     Toast.makeText(act_context, 
//	                         "Error posting story", 
//	                         Toast.LENGTH_SHORT).show();
//	                 }
//					
//				}
//
//	         })
//	         .build();
//	     feedDialog.show();	
}

	@SuppressWarnings("deprecation")
	@SuppressLint("NewApi")
	public void addToCalendar(Context ctx, final String title,
			final String desc, final String tit, final long dtstart,
			final long dtend) {

		Uri eventsUri, reminderuri;

		if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 14) {
			eventsUri = Uri.parse("content://com.android.calendar/events");
			reminderuri = Uri.parse("content://com.android.calendar/reminders");
			ContentValues event = new ContentValues();

			event.put(Events.CALENDAR_ID, 1);
			event.put(Events.TITLE, tit);
			event.put(Events.DESCRIPTION, "SPORTIZZA");
			event.put(Events.DTSTART, dtstart);
			event.put(Events.DTEND, dtend);
			event.put(Events.STATUS, 1);
			event.put(Events.EVENT_COLOR, Color.BLUE);
			event.put(Events.HAS_ALARM, 1);
			event.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone
					.getDefault().getID());

			// To Insert
			Log.v("suraj", "Event =" + TimeZone.getDefault().getID());

			Uri uri = ctx.getContentResolver().insert(
					CalendarContract.Events.CONTENT_URI, event);

			long eventID = Long.parseLong(uri.getLastPathSegment());

			ContentValues reminders = new ContentValues();
			reminders.put(Reminders.EVENT_ID, eventID);
			reminders.put(Reminders.METHOD, Reminders.METHOD_ALERT);
			reminders.put(Reminders.MINUTES, 15);

			ctx.getContentResolver().insert(
					CalendarContract.Reminders.CONTENT_URI, reminders);

			Log.v("suraj", "Reminder =" + reminders);

		} else if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 8
				&& Integer.parseInt(android.os.Build.VERSION.SDK) < 14) {
			eventsUri = Uri.parse("content://com.android.calendar/events");
			reminderuri = Uri.parse("content://com.android.calendar/reminders");

			ContentValues event = new ContentValues();

			event.put(Events.CALENDAR_ID, 1);
			event.put(Events.TITLE, tit);
			event.put(Events.DESCRIPTION, "SPORTIZZA");
			event.put(Events.DTSTART, dtstart);
			event.put(Events.DTEND, dtend);
			event.put(Events.STATUS, 1);
			event.put(Events.HAS_ALARM, 1);
			event.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone
					.getDefault().getID());

			// To Insert
			Log.v("suraj", "Event =" + TimeZone.getDefault().getID());

			Uri uri = ctx.getContentResolver().insert(eventsUri, event);

			long eventID = Long.parseLong(uri.getLastPathSegment());

			ContentValues reminders = new ContentValues();
			reminders.put(Reminders.EVENT_ID, eventID);
			reminders.put(Reminders.METHOD, Reminders.METHOD_ALERT);
			reminders.put(Reminders.MINUTES, 15);

			ctx.getContentResolver().insert(reminderuri, reminders);

			Log.v("suraj", "Reminder =" + reminders);
		}
	}

	@Override
	public int getViewType() {
		return Rowtype.TEAM_ROW.ordinal();
	}

	private static class ViewHolder {
		final ImageView team_image1;
		final ImageView team_image2;
		final TextView teamchamp;
		final TextView teamname1;
		final TextView teamname2;
		final TextView teamdate;
		final TextView teamday;
		final TextView sport_name;
		final TextView channel1;
		final TextView channel2;
		final TextView channel3;
		final TextView game_txt;
		final TextView match_txt;
		final Button t_follow1;
		final Button t_follow2;
		final Button btn_team_cal;
		final Button ticket;
		
		final LinearLayout linearLayout;
		
		private ViewHolder(LinearLayout linearLayout, ImageView team_image1, ImageView team_image2,TextView game_txt, TextView match_txt,
				TextView teamchamp, TextView teamname1, TextView teamname2,
				 TextView teamday, TextView teamdate,
				TextView sport_name, TextView channel1, TextView channel2,
				TextView channel3, Button t_follow1, Button t_follow2,
				Button team_cal,Button ticket) {
			this.team_image1 = team_image1;
			this.team_image2 = team_image2;
			
			this.game_txt=game_txt;
			this.match_txt= match_txt; 
			this.teamchamp = teamchamp;
			this.teamname1 = teamname1;
			this.teamname2 = teamname2;
			this.teamdate = teamdate;
			this.teamday = teamday;
			this.ticket=ticket;
			this.sport_name = sport_name;
			this.channel2 = channel2;
			this.channel1 = channel1;
			this.channel3 = channel3;
			this.t_follow1 = t_follow1;
			this.t_follow2 = t_follow2;
			this.btn_team_cal = team_cal;
			this.linearLayout=linearLayout;
		}

	}
/*
	private class imageTask extends AsyncTask<String, Void, Bitmap> {
		ImageView imageView = null;

		imageTask(ImageView iv) {
			this.imageView = iv;
		}

		@Override
		protected Bitmap doInBackground(String... params) {
			try {
				return download_Image(params[0]);
			} catch (OutOfMemoryError e) {
				return null;
			}

		}

		@Override
		protected void onPostExecute(Bitmap result) {
			Bitmap output;
			Canvas canvas;
			float roundPx;
			if (result == null) {
				InputStream is = null;
				try {
					if (player.gettablet() == false) {
						is = act_context
								.getResources()
								.getAssets()
								.open("default_images/phone/"
										+ player.getsport_code() + ".png");
					} else if (player.gettablet() == true) {
						is = act_context
								.getResources()
								.getAssets()
								.open("default_images/phone/"
										+ player.getsport_code() + "@2x.png");
					}
					result = BitmapFactory.decodeStream(is);
				} catch (Exception e) {
					result = BitmapFactory.decodeResource(
							act_context.getResources(), R.drawable.ic_launcher);
				}

				output = Bitmap.createBitmap(result.getWidth(),
						result.getHeight(), Bitmap.Config.ARGB_8888);
				canvas = new Canvas(output);

				Paint paint = new Paint();
				Rect rect = new Rect(0, 0, result.getWidth(),
						result.getHeight());
				RectF rectF = new RectF(rect);
				roundPx = 8f;

				paint.setAntiAlias(true);
				canvas.drawARGB(0, 0, 0, 0);
				paint.setColor(0xff424242);
				canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
				paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
				canvas.drawBitmap(result, rect, rect, paint);

				imageView.setImageBitmap(output);
				imageView.setScaleType(ScaleType.FIT_CENTER);
			} else {
				output = Bitmap.createBitmap(result.getWidth(),
						result.getHeight(), Bitmap.Config.ARGB_8888);
				canvas = new Canvas(output);

				Paint paint = new Paint();
				Rect rect = new Rect(0, 0, result.getWidth(),
						result.getHeight());
				RectF rectF = new RectF(rect);
				roundPx = 8f;

				paint.setAntiAlias(true);
				canvas.drawARGB(0, 0, 0, 0);
				paint.setColor(0xff424242);
				canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
				paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
				canvas.drawBitmap(result, rect, rect, paint);

				imageView.setImageBitmap(output);
				imageView.setScaleType(ScaleType.FIT_CENTER);
			}
			super.onPostExecute(result);
		}

		private Bitmap download_Image(String url) {
			// ---------------------------------------------------
			Bitmap bm = null;
			try {
				URL aURL = new URL(url);
				URLConnection conn = aURL.openConnection();
				conn.connect();
				InputStream is = conn.getInputStream();
				BufferedInputStream bis = new BufferedInputStream(is);
				bm = BitmapFactory.decodeStream(bis);
				bis.close();
				is.close();
			} catch (Exception e) {
				Log.e("Hub", "Error getting the image from server : ");
				InputStream iss = null;
				try {
					iss = act_context
							.getResources()
							.getAssets()
							.open("default_images/phone/"
									+ player.getsport_code() + ".png");
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				return BitmapFactory.decodeStream(iss);
			}
			return bm;

		}

	}
*/

	public int getImgLoader(String sport_code) {

		int loader = R.drawable.gam;
		
		if(sport_code.equalsIgnoreCase("AFT"))
		{
			loader = R.drawable.aft;
		}else if(sport_code.equalsIgnoreCase("TT"))
		{
			loader = R.drawable.tt;
		}else if(sport_code.equalsIgnoreCase("POL"))
		{
			loader = R.drawable.pol;
		}else if(sport_code.equalsIgnoreCase("SWI"))
		{
			loader = R.drawable.swi;
		}else if(sport_code.equalsIgnoreCase("UFC"))
		{
			loader = R.drawable.ufc;
		}else if(sport_code.equalsIgnoreCase("BAD"))
		{
			loader = R.drawable.bad;
		}else if(sport_code.equalsIgnoreCase("BB"))
		{
			loader = R.drawable.bb;
		}else if(sport_code.equalsIgnoreCase("CRI"))
		{
			loader = R.drawable.cri;
		}else if(sport_code.equalsIgnoreCase("F1"))
		{
			loader = R.drawable.f1;
		}else if(sport_code.equalsIgnoreCase("GAM"))
		{
			loader = R.drawable.gam;
		}else if(sport_code.equalsIgnoreCase("GOL"))
		{
			loader = R.drawable.gol;
		}else if(sport_code.equalsIgnoreCase("HOC"))
		{
			loader = R.drawable.hoc;
		}else if(sport_code.equalsIgnoreCase("ICE"))
		{
			loader = R.drawable.ice;
		}else if(sport_code.equalsIgnoreCase("IND"))
		{
			loader = R.drawable.ind;
		}else if(sport_code.equalsIgnoreCase("MGP"))
		{
			loader = R.drawable.mgp;
		}else if(sport_code.equalsIgnoreCase("NAS"))
		{
			loader = R.drawable.nas;
		}else if(sport_code.equalsIgnoreCase("OLY"))
		{
			loader = R.drawable.oly;
		}else if(sport_code.equalsIgnoreCase("RUG"))
		{
			loader = R.drawable.rug;
		}else if(sport_code.equalsIgnoreCase("SBK"))
		{
			loader = R.drawable.sbk;
		}else if(sport_code.equalsIgnoreCase("SOC"))
		{
			loader = R.drawable.soc;
		}else if(sport_code.equalsIgnoreCase("SPO"))
		{
			loader = R.drawable.spo;
		}else if(sport_code.equalsIgnoreCase("SQU"))
		{
			loader = R.drawable.squ;
		}else if(sport_code.equalsIgnoreCase("TEN"))
		{
			loader = R.drawable.ten;
		}else if(sport_code.equalsIgnoreCase("V8C"))
		{
			loader = R.drawable.v8c;
		}else if(sport_code.equalsIgnoreCase("WRC"))
		{
			loader = R.drawable.wrc;
		}
		else
		{
			loader = R.drawable.gam;
		}
		return loader;
	}

}
